<template>
  <!-- 顶部导航栏 -->
  <div class="top-header">
    <!-- 网站Logo和名称 -->
    <div class="logo-container" @click="navigateToHome">
      <div class="logo">EDU</div>
      <div class="site-name">教育共享平台</div>
    </div>
    <!-- 导航菜单 -->
    <div class="nav-links">
      <div
        v-for="(item, index) in navItems"
        :key="index"
        class="nav-item"
        :class="{ active: currentPath === item.path }"
        @click="navigateTo(item.path)"
      >
        <component
          :is="getIconComponent(item.name)"
          class="nav-icon"
        />
      </div>
      <!-- 添加课程按钮 - 只对教师和管理员显示 -->
      <div 
        v-if="isTeacherOrAdmin()" 
        class="add-course-btn" 
        @click="goToAddCourse"
      >
        <AddCourseIcon class="nav-icon" />
      </div>
    </div>
    <!-- 用户区域 -->
    <div class="user-area">
      <!-- 搜索框 -->
      <div class="search-box">
        <div class="search-input-wrapper">
          <i class="el-icon-search search-icon"></i>
          <input 
            type="text" 
            v-model="searchKeyword"
            @input="handleSearchInput"
            @focus="handleFocus"
            @blur="handleBlur"
            @keyup.enter="handleSearch"
            placeholder="搜索课程..." 
          />
          <el-button 
            type="primary" 
            class="search-button"
            @click="handleSearch"
          >搜索</el-button>
        </div>
        <!-- 自动补全下拉框 -->
        <div class="suggestions-dropdown" v-show="showDropdown && suggestions.length > 0">
          <div 
            v-for="(item, index) in suggestions" 
            :key="index"
            class="suggestion-item"
            @click="selectSuggestion(item)"
            @mousedown.prevent
          >
            {{ item }}
          </div>
        </div>
      </div>
      <!-- 欢迎信息 -->
      <div class="welcome">欢迎你，{{ userName }}</div>
      <!-- 消息通知 -->
      <div class="notification-icon" @click="navigateTo('/notifications')">
        <el-badge :value="unreadCount" :hidden="!unreadCount" class="notification-badge">
          <el-icon><Bell /></el-icon>
        </el-badge>
      </div>
      <!-- 用户头像下拉菜单 -->
      <el-dropdown @command="handleCommand" trigger="click">
        <span class="el-dropdown-link">
          <div class="user-avatar" v-if="avatarUrl">
            <img :src="avatarUrl" alt="用户头像" class="avatar-img">
          </div>
          <div class="user-avatar" v-else>
            <i class="el-icon-user-solid"></i>
          </div>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="userInfo">个人中心</el-dropdown-item>
            <el-dropdown-item command="myCourses">我的课程</el-dropdown-item>
            <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getUserName, getUnreadNotification } from '@/api/user'
import { Bell } from '@element-plus/icons-vue'
import eventBus from '@/utils/eventBus'
import request from '@/utils/request'
import { isTeacherOrAdmin } from '@/utils/permission'  // 导入权限检查函数
import HomeIcon from '@/components/icons/HomeIcon.vue'
import CourseIcon from '@/components/icons/CourseIcon.vue'
import MyCourseIcon from '@/components/icons/MyCourseIcon.vue'
import AddCourseIcon from '@/components/icons/AddCourseIcon.vue'

const router = useRouter()
const route = useRoute()
const userName = ref('')
const avatarUrl = ref('')
const unreadCount = ref(0)
const searchKeyword = ref('')
const suggestions = ref([])
const showDropdown = ref(false)
let searchTimer = null

/**
 * 导航菜单项配置
 */
const navItems = [
  { name: '首页', path: '/home' },
  { name: '课程', path: '/courses' },
  { name: '我的课程', path: '/my-courses' }
]

/**
 * 计算当前路径以确定激活的导航项
 */
const currentPath = computed(() => {
  // 匹配当前路径的前缀
  for (const item of navItems) {
    if (route.path.startsWith(item.path)) {
      return item.path
    }
  }
  return ''
})

/**
 * 导航到指定路径
 * @param {string} path - 目标路径
 */
const navigateTo = (path) => {
  router.push(path)
}

/**
 * 导航到首页
 */
const navigateToHome = () => {
  router.push('/home')
}

/**
 * 跳转到添加课程页面
 */
const goToAddCourse = () => {
  router.push('/course/create')
}

/**
 * 处理用户下拉菜单选项
 * @param {string} command - 菜单命令
 */
const handleCommand = (command) => {
  if (command === 'userInfo') {
    router.push('/user')
  } else if (command === 'myCourses') {
    router.push('/my-courses')
  } else if (command === 'logout') {
    sessionStorage.removeItem('token')
    localStorage.removeItem('token')
    router.push('/login')
  }
}

/**
 * 获取用户信息
 */
const fetchUserInfo = async () => {
  // 检查是否有token
  const token = sessionStorage.getItem('token') || localStorage.getItem('token')
  if (!token) {
    userName.value = '游客'
    avatarUrl.value = ''
    return
  }

  try {
    const response = await getUserName()
    
    if (response && response.code === 200 && response.data) {
      userName.value = response.data.userName || '用户'
      
      if (response.data.ossImages && response.data.ossImages.length > 0) {
        const headImage = response.data.ossImages.find(img => img.relationType === 'head')
        if (headImage) {
          avatarUrl.value = headImage.url
        }
      } else if (response.data.avatarUrl) {
        if (!response.data.avatarUrl.startsWith('http')) {
          const baseURL = process.env.VUE_APP_BASE_API || ''
          avatarUrl.value = `${baseURL}${response.data.avatarUrl}`
        } else {
          avatarUrl.value = response.data.avatarUrl
        }
      } else {
        avatarUrl.value = ''
      }
    }
  } catch (error) {
    userName.value = '游客'
    avatarUrl.value = ''
  }
}

/**
 * 获取未读通知数量
 */
const fetchUnreadCount = async () => {
  try {
    const response = await getUnreadNotification()
    if (response.code === 200) {
      unreadCount.value = Number(response.data) || 0
    } else {
      unreadCount.value = 0
    }
  } catch (error) {
    unreadCount.value = 0
  }
}

/**
 * 监听路由变化
 */
watch(() => route.path, (newPath) => {
  const authPaths = ['/login', '/register', '/phone-login', '/forgot-password', '/phone-reset']
  const token = sessionStorage.getItem('token') || localStorage.getItem('token')
  if (!authPaths.includes(newPath) && token) {
    fetchUserInfo()
    fetchUnreadCount()
  }
})

/**
 * 监听通知更新事件
 */
const handleNotificationUpdate = () => {
  fetchUnreadCount()
}

/**
 * 组件挂载时
 */
onMounted(() => {
  eventBus.on('avatar-updated', (newAvatarUrl) => {
    if (newAvatarUrl) {
      avatarUrl.value = newAvatarUrl
    } else {
      fetchUserInfo()
    }
  })

  eventBus.on('notification-updated', handleNotificationUpdate)

  fetchUserInfo()
  fetchUnreadCount()
})

/**
 * 组件卸载前
 */
onUnmounted(() => {
  eventBus.off('avatar-updated')
  eventBus.off('notification-updated', handleNotificationUpdate)
})

/**
 * 处理输入框获得焦点
 */
const handleFocus = () => {
  showDropdown.value = true
}

/**
 * 处理输入框失去焦点
 */
const handleBlur = () => {
  // 延迟隐藏下拉框，以便点击事件能够触发
  setTimeout(() => {
    showDropdown.value = false
  }, 200)
}

/**
 * 处理搜索输入
 */
const handleSearchInput = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  showDropdown.value = true
  
  if (searchKeyword.value.trim()) {
    searchTimer = setTimeout(() => {
      fetchSuggestions()
    }, 300)
  } else {
    suggestions.value = []
  }
}

/**
 * 获取搜索建议
 */
const fetchSuggestions = async () => {
  try {
    const response = await request({
      url: '/searchService/search/autoSuggest',
      method: 'get',
      params: {
        keyword: searchKeyword.value
      }
    })
    
    if (response.code === 200) {
      suggestions.value = response.data || []
    }
  } catch (error) {
    suggestions.value = []
  }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      name: 'search',
      query: {
        keyword: searchKeyword.value.trim()
      }
    })
    suggestions.value = []
    showDropdown.value = false
  }
}

/**
 * 选择建议项
 */
const selectSuggestion = (suggestion) => {
  searchKeyword.value = suggestion
  suggestions.value = []
  showDropdown.value = false
  handleSearch()
}

const getIconComponent = (name) => {
  switch (name) {
    case '首页':
      return HomeIcon
    case '课程':
      return CourseIcon
    case '我的课程':
      return MyCourseIcon
    default:
      return null
  }
}
</script>

<style scoped>
/* 顶部导航栏容器 */
.top-header {
  height: 70px;  /* 增加导航栏高度 */
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 50px;  /* 增加两侧内边距 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);  /* 增强阴影效果 */
  position: sticky;
  top: 0;
  z-index: 1000;
}

/* Logo容器 */
.logo-container {
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
  min-width: 260px;  /* 设置最小宽度，确保Logo区域不会被压缩 */
}

/* Logo样式 */
.logo {
  background-color: #1c86ee;
  color: white;
  font-weight: bold;
  padding: 10px 20px;  /* 增加内边距 */
  border-radius: 8px;  /* 增加圆角 */
  font-size: 22px;  /* 增大字体 */
  letter-spacing: 1px;  /* 添加字间距 */
  box-shadow: 0 2px 8px rgba(28, 134, 238, 0.2);  /* 添加阴影效果 */
}

/* 网站名称 */
.site-name {
  font-size: 22px;  /* 增大字体 */
  font-weight: bold;
  color: #333;
  letter-spacing: 0.5px;  /* 添加字间距 */
}

/* 导航链接容器 */
.nav-links {
  display: flex;
  gap: 40px;  /* 增加按钮之间的间距 */
  margin-left: 60px;  /* 减小与logo的间距 */
  align-items: center;  /* 确保垂直居中 */
  flex: 1;  /* 添加flex属性以占据剩余空间 */
}

/* 导航项样式 */
.nav-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  cursor: pointer;
  position: relative;
  color: #666;
  transition: all 0.3s ease;
  border-radius: 6px;
  width: 48px;
  height: 48px;
  overflow: hidden;

  .nav-icon {
    width: 24px;
    height: 24px;
    display: block;
  }

  &:hover {
    background-color: #f0f7ff;
    color: var(--el-color-primary);
  }

  &.active {
    color: var(--el-color-primary);
    background-color: #f0f7ff;
  }
}

.nav-item.active::after {
  display: none;
}

/* 添加课程按钮 */
.add-course-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  background-color: var(--el-color-primary);
  color: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 20px;
  width: 48px;
  height: 48px;
  overflow: hidden;

  .nav-icon {
    width: 24px;
    height: 24px;
    display: block;
  }

  &:hover {
    background-color: var(--el-color-primary-dark-2);
    transform: translateY(-2px);
  }
}

/* 用户区域容器 */
.user-area {
  display: flex;
  align-items: center;
  gap: 20px;
  min-width: 400px;  /* 设置最小宽度，确保用户区域不会被压缩 */
  justify-content: flex-end;  /* 将用户区域内容靠右对齐 */
}

/* 搜索框容器 */
.search-box {
  position: relative;
  width: 250px;
  margin: 0 20px;
}

/* 搜索输入框包装器 */
.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 16px;
  padding: 4px 8px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid transparent;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.search-input-wrapper:hover {
  background-color: #fff;
  border-color: #e0e7ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-input-wrapper:focus-within {
  background-color: #fff;
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.12);
}

/* 搜索图标 */
.search-icon {
  color: #909399;
  margin: 0 8px;
  font-size: 18px;
  transition: color 0.3s;
}

.search-input-wrapper:focus-within .search-icon {
  color: #409eff;
}

/* 输入框 */
.search-input-wrapper input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  height: 32px;
  font-size: 14px;
  color: #303133;
  width: 100%;
  padding: 0 8px;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.search-input-wrapper input::placeholder {
  color: #909399;
  transition: color 0.3s;
}

.search-input-wrapper:focus-within input::placeholder {
  color: #c0c4cc;
}

/* 搜索按钮 */
.search-button {
  margin-left: 8px;
  height: 32px;
  padding: 0 16px;
  border-radius: 14px;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 0.5px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

.search-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #66b1ff, #409eff);
}

.search-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
}

/* 欢迎信息 */
.welcome {
  font-size: 14px;
  color: #666;
}

/* 用户头像下拉菜单 */
.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

/* 用户头像容器 */
.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  font-size: 20px;
}

/* 用户头像图片 */
.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 消息通知图标 */
.notification-icon {
  position: relative;
  cursor: pointer;
  font-size: 20px;
  color: #606266;
  transition: color 0.3s;
}

.notification-icon:hover {
  color: #1c86ee;
}

/* 通知徽章 */
.notification-badge :deep(.el-badge__content) {
  background-color: #f56c6c;
}

/* 下拉菜单中的徽章 */
.dropdown-badge :deep(.el-badge__content) {
  transform: scale(0.8);
  right: -15px;
}

/* 移动端适配 */
@media (max-width: 1200px) {
  .search-box {
    width: 200px;
  }
  
  .search-box input {
    width: 150px;
  }
}

@media (max-width: 992px) {
  .top-header {
    padding: 0 20px;
  }
  
  .nav-links {
    gap: 15px;
  }
  
  .search-box {
    display: none;
  }
}

@media (max-width: 768px) {
  .site-name {
    display: none;
  }
  
  .nav-links {
    display: none;
  }
  
  .user-area {
    gap: 10px;
  }
  
  .welcome {
    display: none;
  }
}

/* 建议下拉框 */
.suggestions-dropdown {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  right: 0;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-height: 320px;
  overflow-y: auto;
  z-index: 1000;
  border: 1px solid #ebeef5;
  padding: 6px 0;
}

.suggestion-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  margin: 0 6px;
  border-radius: 12px;
}

.suggestion-item:hover {
  background-color: #ecf5ff;
  color: #409eff;
  padding-left: 20px;
}

.suggestion-item::before {
  content: '';
  width: 4px;
  height: 4px;
  background-color: #909399;
  border-radius: 50%;
  margin-right: 8px;
  transition: all 0.2s ease;
}

.suggestion-item:hover::before {
  background-color: #409eff;
  transform: scale(1.2);
}

/* 自定义滚动条 */
.suggestions-dropdown::-webkit-scrollbar {
  width: 6px;
}

.suggestions-dropdown::-webkit-scrollbar-track {
  background: transparent;
}

.suggestions-dropdown::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.suggestions-dropdown::-webkit-scrollbar-thumb:hover {
  background-color: #c0c4cc;
}

.nav-item :deep(.custom-icon) {
  width: 24px;
  height: 24px;
}
</style> 